package luj.tool.jnproxyan.proxy.network.socks.actor.root.message.request.connect.finish2;

import luj.net.api.server.ConnectionAcceptInitializer;
import luj.tool.jnproxyan.proxy.network.socks.actor.root.Socks5Actor;
import luj.tool.jnproxyan.proxy.network.socks.reply.SocksReplyMaker;
import luj.tool.jnproxyan.proxy.network.socks.request.SocksRequest;
import luj.tool.jnproxyan.proxy.network.ssh.tunnel.SshTunnel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * SSH
 */
@Component
final class OnConnectFinish2 implements Socks5Actor.Handler<ConnectFinish2Msg> {

  @Override
  public void onHandle(Context ctx) {
    ConnectFinish2Msg msg = ctx.getMessage(this);
    SshTunnel result = msg.connectResult();

    Socks5Actor self = ctx.getActorState(this);
    SocksRequest request = getRequest(self, msg);

    LOG.debug("连上网站：{} - {}", request.getReqId(), request.getBody().getTargetHost());
    request.setStatus("连接服务器成功");
    request.setP2sConn2(result);

    ConnectionAcceptInitializer.Connection c2pConn = request.getC2pConn();
    c2pConn.write(new SocksReplyMaker(c2pConn).make(SUCCEEDED));
    c2pConn.flush();
  }

  private SocksRequest getRequest(Socks5Actor self, ConnectFinish2Msg msg) {
    Long reqId = msg.reqId();
    SocksRequest request = self.getRequestMap().get(reqId);
    return checkNotNull(request, reqId);
  }

  private static final Logger LOG = LoggerFactory.getLogger(OnConnectFinish2.class);

  private static final int SUCCEEDED = 0x00;
}
